<?php


function getRootPath()
{
	$root_path = str_replace(SYSDIR.'/', '', BASEPATH);	
	return $root_path;
}



function getHours()
{
	$hours_arr = array();
	for($i=0; $i<=23; $i++) {
		$hour = sprintf("%01d", $i);
		$hours_arr[$hour] = $hour;
	}
	return $hours_arr;	
}

function getMinutes()
{
	$minutes_arr = array();
	for($i=0; $i<=59; $i++) {
		$minutes = sprintf("%01d", $i);
		$minutes_arr[$minutes] = $minutes;
	}
	return $minutes_arr;
}

function vardump($data, $exit=false)
{
	echo "<pre>";
	print_r($data);
	echo "</pre>";
	if( $exit ) {
		exit;	
	}
}

function userLog($ip,$browser)
{
	$CI =& get_instance();
	return $CI->common_model->userLog($ip,$browser);
}

function trackUser()
{
	$CI =& get_instance();
	return $CI->common_model->trackUser();
}

function getAllTimeZones()
{
	$CI =& get_instance();
	return $CI->common_model->getAllTimeZones();
}

function DB_modification_logs($module)
{
	$CI =& get_instance();
	return $CI->common_model->DB_modification_logs($module);
}


function check_module($module_url, $permission)
{
	$CI =& get_instance();
	return $CI->common_model->check_module($module_url, $permission);
}

function check_permission($module_url, $permission)
{
	$CI =& get_instance();
	return $CI->common_model->check_permission($module_url, $permission);
}

function getUserModules($user_id)
{
	$CI =& get_instance();
	return $CI->common_model->getUserModules($user_id);
}

function getModules()
{
	$CI =& get_instance();
	return $CI->common_model->getModules();
}

function getVdnLocations()
{
	$CI =& get_instance();
	return $CI->common_model->getVdnLocations();
}

function getAllContext()
{
	$CI =& get_instance();
	return $CI->common_model->getAllContext();
}

function getAllLoactions()
{
	$CI =& get_instance();
	return $CI->common_model->getAllLoactions();
}


function getAgentPrimarySkill($membername)
{
	$CI =& get_instance();
	$CI->load->model('agent_model');
	$result = $CI->agent_model->getAgentPrimarySkill($membername);
	return $result;
}


function getAllagent()
{
	$CI =& get_instance();
	$CI->load->model('agent_model');
	$result = $CI->agent_model->getAllagent();
	return $result;
}

function getAllskills()
{
	$CI =& get_instance();
	$CI->load->model('skill_model');
	$result = $CI->skill_model->getAllskills();
	return $result;
}

function parseAgentExt($agent_name)
{
	return str_replace('Agent/', '', $agent_name);	
}

function get_all_acd_servers()
{
	$CI =& get_instance();
	$CI->load->model('acd_server_model');
	$result = $CI->acd_server_model->getAllRecords();
	return $result;
}

function getCallRoutingStrategies()
{
	$array = array('leastrecent');
	$data = array();
	foreach($array as $val) {
		$data[$val] = $val;	
	}
	return $data;
}

function getValueFromArr($array, $index, $return_not_found = '-')
{
	if( isset($array[$index]) )
	{
		return $array[$index];
	}
	else
	{
		return $return_not_found;	
	}
}

function create_indexed_array($data, $fields = array('key'=>'id', 'value'=>'name'))
{
	$result_arr = array();
	foreach ( $data as $row) 
	{
		if( isset($row->$fields['key']) ) {
			$key = $row->$fields['key'];
		} elseif( isset($row[$fields['key']]) ) {
			$key = $row[$fields['key']];
		}
		if( isset($row->$fields['value']) ) {
			$value = $row->$fields['value'];
		} elseif( isset($row[$fields['value']]) ) {
			$value = $row[$fields['value']];
		}
		$result_arr[$key] = $value;
	}
	return $result_arr;
}


function create_select($name, $data, $selected = '', $fields = array(), $attributes = '', $empty_option_name='')
{	
	$html = "<select name='{$name}' id='{$name}' {$attributes} >";
	$html .= create_Options($data, $selected, $fields, $empty_option_name);
	$html .= "</select>";
	return $html;
}




function create_Options($data, $selected = '', $fields = array(), $empty_option_name)
{
	if( $empty_option_name != '' ) {
		$html = '<option value=""> '.$empty_option_name.' </option>'; 
	} else {
		$html = '<option value=""> select </option>'; 
	}
	if( count($fields) > 0 and is_array($fields))
	{
		foreach ( $data as $row) 
		{
			if( isset($row->$fields['value']) ) {
				$value = $row->$fields['value'];
			} elseif( isset($row[$fields['value']]) ) {
				$value = $row[$fields['value']];
			}
				
			if( isset($row->$fields['label']) ) {
				$label = $row->$fields['label'];
			} elseif( isset($row[$fields['label']]) ) {
				$label = $row[$fields['label']];
			}
			$_selected = ( $value == $selected ) ? 'selected="selected"':'';
			$html .= '<option '.$_selected.' value="'.$value.'">'.$label.'</option>';
			
		}
	}
	else
	{
		foreach ( $data as $value=>$label) 
		{	
			$_selected = ( $value == $selected ) ? 'selected="selected"':'';
			$html .= '<option '.$_selected.' value="'.$value.'">'.$label.'</option>';	
			
		}
	}
	
	return $html;
}


if ( ! function_exists('imageUrl'))
{
	function imageUrl()
	{
		$CI =& get_instance();
		return $CI->config->slash_item('base_url_images');
	}
}

if ( ! function_exists('link_css'))
{

  function link_css($file)
  {
	  $CI =& get_instance();
	  $base_url = base_url();
	  $base_url_offset = $CI->config->slash_item('base_url_offset');
	  if( $base_url_offset != '' ) {
		  $base_url = str_replace($base_url_offset, '', $base_url);
	  }
       return '<link type="text/css" rel="stylesheet" href="'.$base_url.'css/'.$file.'">';
  }

}

if ( ! function_exists('link_js') )
{

  function link_js($file)
  {
	  $CI =& get_instance();
	  $base_url = base_url();
	  $base_url_offset = $CI->config->slash_item('base_url_offset');
	  if( $base_url_offset != '' ) {
		  $base_url = str_replace($base_url_offset, '', $base_url);
	  }
      return '<script type="text/javascript" src="'.$base_url.'js/'.$file.'"></script>';
  }

}

if(!function_exists('userLog'))
{
 	function userLog($ip,$browser)
	{
		$CI =& get_instance();
		
		$user_id = $CI->session->userdata('sess_user_id');
		$username=  $CI->session->userdata('sess_username');
		$fullname=$CI->session->userdata('sess_full_name');
		$session_id=$CI->session->userdata('session_id');
		$userType=  $CI->session->userdata('sess_user_type');
		$record = array(
						'user_id' 	=> $user_id,
						'username' 	=> $username,
						'full_name'=>$fullname,
						'login_at' => date('Y-m-d H:i:s'),
						'user_type' =>$userType,
						'browser'=>$browser,
						'ip' => $ip,
						'session_id'=>$session_id
					);
		$CI->db->insert("user_log", $record);			
		
	}
} 


if(!function_exists('trackUser'))
{
 	function trackUser()
	{
		$CI =& get_instance();
		$session_id=$CI->session->userdata('session_id');
		$user_id = $CI->session->userdata('sess_user_id');
		if($user_id>0)
		{
			$uri = $CI->uri->segment(1);
			if( $CI->uri->segment(2) != '' ){
				$uri .= '/'. $CI->uri->segment(2);	
			}
			
			$sql="Select uri from user_log where user_id=$user_id and session_id="."'".$session_id."'";
			$result=$CI->db->query($sql)->row();
			$array = @explode(',',$result->uri);
 			if( ! empty($array[0]) ) 
			{
				if(!in_array($uri,$array))
				{
					$uri=$result->uri.",".$uri;
					$CI->db->where('user_id',$user_id);
					$CI->db->where('session_id',$session_id);
					$record=array(
									'uri'=>$uri
								);
						$CI->db->update("user_log", $record);
				}			
			}
			else
			{
				$CI->db->where('user_id',$user_id);
				$CI->db->where('session_id',$session_id);
				$record=array(
								'uri'=>$uri
							);
				$CI->db->update("user_log", $record);
			}
		}
	}
} 

//______________________________ Listing Function ____________________________________

if (!function_exists("showGridListingData")) {

    function showGridListingData($sql, $data) 
	{
		$CI = & get_instance();
		foreach ($_POST as $key => $val) {
            $key = str_replace(".", "_", $key);
            $_POST[$key] = $val;
        }
        $CI->session->set_userdata($_POST);
		//vardump($CI->session->all_userdata());
		
        $controller_base_path = $data["dataOthers"]['controller_base_path'];
        $customWhere = isset($data['customWhere']) ? $data['customWhere'] : '';
		
       
        $CI->load->library("pagination");
        $sess_prefix = "list_sess_" . $CI->uri->segment(1) . '_'; // controller name
		$dataFields = $data["dataFields"];
        $whereSearch = " where 1=1 ";
        $dataFieldsLables = "";

        //debug($CI->session->userdata);
        if (isset($dataFields) && count($dataFields) > 0) {
            foreach ($dataFields as $dataFieldsKey => $dataFieldsVal) {
                if (isset($dataFieldsVal['skip_db_select']) && $dataFieldsVal['skip_db_select'] == 1) {
                    continue;
                }
                //print_r($dataFieldsVal);
                $dataFieldType = isset($dataFieldsVal["dataFieldType"]) ? $dataFieldsVal["dataFieldType"] : '';
                
                 //$dataFieldsLables .= $dataFieldsKey . ",";
                //$sessionKey = str_replace("____", ".", $dataFieldsKey);
                $sessionKey = str_replace(".", "_", $dataFieldsKey);
                $sessionKey = $sess_prefix . $sessionKey;
                if (trim($CI->session->userdata($sessionKey)) != "" ) {
                    //$sessionKey=$CI->db->escape($sessionKey);
                    $dataValue = trim($CI->session->userdata($sessionKey));
					
                    if ($dataFieldType == "text") {
                        if (isset($dataFieldsVal["db_formater"]) && $dataFieldsVal["db_formater"] != "") {
                            $dataFieldsKey = str_replace("{field}", $dataFieldsKey, $dataFieldsVal["db_formater"]);
                            $whereSearch .= "	AND $dataFieldsKey LIKE '%" . trim($CI->db->escape($dataValue), "'") . "%' ";
                        }else {
                            $whereSearch .= "	AND $dataFieldsKey LIKE '%" . trim($CI->db->escape($dataValue), "'") . "%' ";
                        }
                    }
                    if ($dataFieldType == "combo") {
                        $whereSearch .= "	AND $dataFieldsKey = '$dataValue' ";
                    }
                }
                if (isset($dataFieldsVal['field_alias']) && !empty($dataFieldsVal['field_alias'])) {
                    $dataFieldsKey = $dataFieldsKey . " as " . $dataFieldsVal['field_alias'];
                }
                $dataFieldsLables .= $dataFieldsKey . ",";
            }

            $dataFieldsLables = substr_replace($dataFieldsLables, "", -1);

            //echo $whereSearch;
        }
        if (trim($customWhere) != "") {
            $whereSearch .= " $customWhere ";
        }
        $GET = $CI->input->get(NULL, true);
        


        $order_by = '';
        if (isset($_GET['sort_by']) && $_GET['sort_by'] != '') {
            $sort_by = $_GET['sort_by'];
            if (isset($_GET['sort_order']) && ($_GET['sort_order'] == 'asc' || $_GET['sort_order'] == 'desc')) {
                $sort_order = $_GET['sort_order'];
            } else {
                $sort_order = 'asc';
            }

            $order_by = " order by {$sort_by} {$sort_order} ";
        }
        if (empty($order_by))
            $order_by = (!empty($data['defaultSort']) ? $data['defaultSort'] : "");

        $config['per_page'] = 10;

        if ($sql != '') {
            $startFrom = $CI->input->get('per_page') ? $CI->input->get('per_page') : 0;
            $LIMIT = "LIMIT $startFrom ,  " . $config['per_page'] . " ";

            $sql = "SELECT SQL_CALC_FOUND_ROWS $dataFieldsLables {$sql} {$whereSearch} $order_by {$LIMIT}";
            //exit;
           // debug($sql,true);
            $results = $CI->db->query($sql)->result_array();
            //debug($CI->db->last_query(), true);
            $export = $CI->input->get('export');
            $export_type = $CI->input->get('export_type');
            if (count($results) > 0) {
                if ($export == 1 && $export_type == 'csv') {
                    $data["results"] = $results; //getTotalRecs( $dataFieldsLables ,  $tableName , "$whereSearch $orderBy", "", $customSelect, $customFrom, $customWhere);
                    exportListingToCSV($data);
                    exit;
                }
            }

            $sql = "SELECT FOUND_ROWS() as cnt";

            $total_record = $CI->db->query($sql)->row_array();
            $getTotalRecsCounts = $total_record['cnt'];
        }
        $config['base_url'] = base_url() . $controller_base_path . '?' . time();
        $config['total_rows'] = $total_record['cnt'];
        $config['full_tag_open'] = '<p>';
        $config['full_tag_close'] = '</p>';
        $perPage = $config['per_page'];
        $CI->config->set_item('enable_query_strings', TRUE);
        $CI->pagination->initialize($config);
        $data["results"] = $results;
        $data['total_rows'] = $config['total_rows'];
        $data['start'] = $startFrom + 1;
        $data['end'] = $startFrom + $config['per_page'];
        //$CI->load->view('admin/listing', $data);
        $CI->load->view('gridlisting', $data);
    }

}

if ( ! function_exists('base_url_2'))
{
	function base_url_2()
	{
		$CI =& get_instance();
		$base_url = $CI->config->slash_item('base_url');
		$base_url_offset = $CI->config->slash_item('base_url_offset');
		return str_replace($base_url_offset, '', $base_url);
	}
}







?>

